package com.acane.instagram.feature.collection

import android.content.Context
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.IOException
import java.io.File
import java.io.FileOutputStream

class CollectionViewModel
    //savedStateHandle: SavedStateHandle
: ViewModel() {
    //private val postPosition: String = checkNotNull(savedStateHandle[COLLECTION_POST_POSITION])
    private val userId = SessionManager.currentUser?.id

    var caption by mutableStateOf("")

    private val _postDatum = MutableStateFlow<List<PostInfo>>(emptyList())
    val postDatum: MutableStateFlow<List<PostInfo>> = _postDatum

//    fun initPostData(userId: String) {
//        viewModelScope.launch {
//            _postDatum.value = MyRetrofitDatasource.getCollectionPostList(userId).data ?: emptyList()
//            Log.d("CollectionViewModel", "收藏帖子列表: ${_postDatum.value}")
//        }
//    }
    // 修改为返回 Job 用于同步
    private fun loadData(): Job = viewModelScope.launch {
        _postDatum.value = userId?.let { MyRetrofitDatasource.getCollectionPostList(it).data } ?: emptyList()
        Log.d("CollectionViewModel", "收藏帖子列表: ${_postDatum.value}")
    }

    fun initPostData() {
        viewModelScope.launch {
            loadData().join() // 等待数据加载完成
        }
    }
    private fun loadInitialData() {
        viewModelScope.launch {
            // 步骤 1：先获取主数据
            loadData().join() // 等待数据加载完成

            // 步骤 2：处理后续过滤
            loadGridPostData()
            //loadVideoPostData()

            // 验证数据
            Log.d("CollectionViewModel", "Grid数据: ${gridPostData.value}")
            Log.d("CollectionViewModel", "Video数据: ${videoPostData.value}")
        }
    }

    init {
        loadInitialData()
    }

    suspend fun getPostPosition(postId: String, userId: String) : Int
    {
        val postData = MyRetrofitDatasource.getCollectionPostList(userId).data
        if (postData != null) {
            return postData.indexOfFirst { it.id == postId }
        }
        return 0
    }

    val gridBoxInfo: MutableStateFlow<Map<PostInfo, String>> = MutableStateFlow(emptyMap())
    private val _gridPostData = MutableStateFlow<List<PostInfo>>(emptyList())
    val gridPostData: MutableStateFlow<List<PostInfo>> = _gridPostData
    private val _videoPostData = MutableStateFlow<List<PostInfo>>(emptyList())
    val videoPostData: MutableStateFlow<List<PostInfo>> = _videoPostData
    fun loadGridPostData() {
        val gridPosts = mutableListOf<PostInfo>()
        val videoPosts = mutableListOf<PostInfo>()

        postDatum.value.forEach { post ->
            when (post.showRange) {
                "grid_and_reels" -> {
                    if (post.urls.size == 1 && post.urls.first().endsWith(".mp4")) {
                        videoPosts.add(post)
                    }
                    gridPosts.add(post)
                }
                "reels" -> {
                    videoPosts.add(post)
                }
            }
        }

        _gridPostData.value = gridPosts
        _videoPostData.value = videoPosts

        _gridPostData.value.forEach { post ->
            val uris = post.urls
            if (uris.size > 1) {
                gridBoxInfo.value = gridBoxInfo.value + (post to "isGrid")

            } else if (uris.size == 1 && uris.first().endsWith(".mp4")) {

                gridBoxInfo.value = gridBoxInfo.value + (post to "isVideo")
            }
        }
        Log.d("CollectionViewModel", "gridBoxInfo:\n ${gridBoxInfo.value} ")
    }

    // 独立缩略图生成函数
    suspend fun generateVideoThumbnail(
        context: Context,
        videoUrl: String,
        timeMicroSec: Long = 0
    ): ImageBitmap? = withContext(Dispatchers.IO) {
        val retriever = MediaMetadataRetriever()
        try {
            val videoFile = downloadVideo(context, videoUrl)
            if (videoFile != null) {
                retriever.setDataSource(videoFile.absolutePath)
                val bitmap = getFrame(retriever, timeMicroSec)
                videoFile.delete() // 删除临时文件
                return@withContext bitmap
            }
        } catch (e: Exception) {
            Log.e("MeViewModel", "生成缩略图失败", e)
        } finally {
            retriever.release()
        }
        return@withContext null
    }

    private fun downloadVideo(context: Context, videoUrl: String): File? {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(videoUrl)
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                Log.e("MeViewModel", "下载视频失败: $response")
                throw IOException("Unexpected code $response")
            }

            val videoFile = File.createTempFile("video", ".mp4", context.cacheDir)
            FileOutputStream(videoFile).use { fos ->
                response.body?.byteStream()?.use { inputStream ->
                    val buffer = ByteArray(4096)
                    var bytesRead: Int
                    while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                        fos.write(buffer, 0, bytesRead)
                    }
                }
            }
            Log.d("MeViewModel", "视频下载成功: ${videoFile.absolutePath}")
            return videoFile
        }
    }

    fun getFrame(retriever: MediaMetadataRetriever, timeMicroSec: Long): ImageBitmap? {
        return retriever.getFrameAtTime(timeMicroSec)?.let { bitmap ->
            // 优化缩略图尺寸
            Bitmap.createScaledBitmap(
                bitmap,
                bitmap.width / 4,  // 缩小尺寸提升性能
                bitmap.height / 4,
                true
            ).asImageBitmap()
        }
    }
}